/**
 * Created by zhouli on 2019/2/25.
 */
import React from 'react';
import {connect} from 'react-redux';
import {message, Button, Spin} from 'antd';
import {messages, getUrlSearchParams,getToken} from 'share/common';
import LoginService from 'containers/login/login.service';
import QrCode from 'qrcode.react';
import 'styles/login/components/qcode-login/qcode-login.scss';

class QcodeLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: "",

      qcodeIsExpired: false,
      scanSuccess: false,
      qcodeValue: false,

      UUID: "",
    };
    this.REQUEST_TIMER = false
  }

  componentDidMount() {
    //挂载子父组件到父组件
    this.props.onRef(this);
    this.getQcode();
  }

  cancelRequestQcode=()=>{
    this.REQUEST_TIMER = false
  };
  //获取二维码
  getQcode = () => {
    this.setState({
      qcodeIsExpired: false,
      scanSuccess: false
    });
    LoginService.getQcode()
      .then((res) => {
        let Request = new getUrlSearchParams(res.data.link); //实例化
        this.setState({
          qcodeValue: res.data.link,
          UUID: Request.UUID
        }, () => {
          this.REQUEST_TIMER = true;
          //没有 token 再请求
          !(getToken()) && this.requestIsScan(Request.UUID);
        })
      })
      .catch(() => {
        message.error(messages('dashboard.key57'/*获取二维码错误*/));
      })
  };

  //轮询是否已经扫描
  requestIsScan = (uuid) => {
    const {UUID} = this.state;
    let that = this;
    if (that.REQUEST_TIMER) {
      LoginService.getQcodeAuthorization(uuid)
        .then((res) => {
          //没有 token 再请求
          !(getToken()) && that.requestIsScan(UUID);
          if (res.data) {
            that.setState({
              qcodeIsExpired: false,
              scanSuccess: false
            });
            if (res.data.status === "WAITING") {
              //用户扫描了，未确认
              that.setState({
                scanSuccess: true
              })
            }
            if (res.data.status === "LOGGED") {
              //登录成功
              that.setState({
                username: res.data.userOID,
                password: "",//密码说是可以不传
                loginType: "app",
                scanSuccess: true,
              }, () => {
                let login = {
                  username: that.state.username,
                  password: that.state.password,
                  loginType: that.state.loginType,
                  clientName: "",
                  loginId: undefined
                };
                that.props.login(login)
              })
            }
          } else {
            that.setState({
              qcodeIsExpired: true
            });
            that.REQUEST_TIMER = false;
          }
        })
        .catch(() => {
          that.setState({
            qcodeIsExpired: true
          });
          that.REQUEST_TIMER = false;
        })
    }
  };
  //渲染二维码
  renderQcodeValue = () => {
    const {qcodeIsExpired, qcodeValue} = this.state;
    let className = "qcode-img-wrap";
    if (qcodeIsExpired) {
      className = "qcode-img-wrap qcode-img-wrap-expired";
    } else {
      className = "qcode-img-wrap";
    }
    if (qcodeValue) {
      return (
        <div className={className}>
          <QrCode value={qcodeValue}
                  renderAs={"svg"}
                  fgColor={"#000000"}
                  size={180}/>
        </div>
      )
    } else {
      return (<div className="loading-container">
        <Spin size="large"/>
      </div>)
    }
  };

  //二维码已经过期
  renderQcodeIsExpired = () => {
    const {qcodeIsExpired, scanSuccess} = this.state;
    if (qcodeIsExpired && !scanSuccess) {
      return (
        <div>
          <div className="qcode-middle-tips">
            {messages('dashboard.key58'/*二维码已经过期*/)}
          </div>
          <div className="qcode-middle-btn">
            <div className="get-message-code regain-code-btn"  onClick={this.getQcode}>{messages('dashboard.key59'/*重新获取*/)}</div>
          </div>
        </div>
      )
    } else {
      return (<div/>)
    }
  };
  //渲染二维码提示
  renderQcodeValueText = () => {
    const {qcodeValue, scanSuccess} = this.state;
    if (qcodeValue && !scanSuccess) {
      return (<div className="qcode-bottom-tips">
        {messages('login.key25')/*请使用汇联易APP扫码登录*/}
      </div>)
    } else {
      return (<div/>)
    }
  };
  //扫描成功
  renderScanSuccess = () => {
    const {scanSuccess} = this.state;
    if (scanSuccess) {
      return (<div className="qcode-bottom-tips">
        {messages('login.key24')/*二维码扫码成功*/}
      </div>)
    } else {
      return (<div/>)
    }
  };

  render() {
    return (
      <div className="qcode-login">
        {this.renderQcodeValue()}
        {this.renderQcodeIsExpired()}
        {this.renderQcodeValueText()}
        {this.renderScanSuccess()}
      </div>
    )
  }
}

QcodeLogin.propTypes = {
  login: React.PropTypes.func,
};

QcodeLogin.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenant: state.login.tenant
  }
}

export default connect(mapStateToProps)(QcodeLogin);

